<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="RTOS TencentOS-tiny">
    <meta name="description" content="嵌入式 STM32 物联网领域的教程及精彩内容分享">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>04-小小的时钟节拍，撑起了内核半边天 | Mculover666</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Mculover666</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-list" style="zoom: 0.6;"></i>
      
      <span>系列教程</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/posts/578764034/">
          
          <span>STM32CubeMX</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>CSDN</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/download" class="waves-effect waves-light">
      
      <i class="fas fa-download" style="zoom: 0.6;"></i>
      
      <span>资源下载</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Mculover666</div>
        <div class="logo-desc">
            
            嵌入式 STM32 物联网领域的教程及精彩内容分享
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-list"></i>
			
			系列教程
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/posts/578764034/ " style="margin-left:75px">
				  
		          <span>STM32CubeMX</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			CSDN
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/download" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-download"></i>
			
			资源下载
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/4.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">04-小小的时钟节拍，撑起了内核半边天</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                                <span class="chip bg-color">RTOS内功修炼记</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/RTOS/" class="post-category">
                                RTOS
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-08-01
                </div>
                

                

                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="1-知识点回顾-—-Systick"><a href="#1-知识点回顾-—-Systick" class="headerlink" title="1.知识点回顾 — Systick"></a>1.知识点回顾 — Systick</h1><p>STM32中的 SysTick 是一个24位的向下计数定时器，当计到0时，将从RELOAD寄存器中自动重装载定时初值并继续计数，且同时触发中断，SysTick 的主要作用是作为系统的时基，产生一个周期性的中断信号。</p>
<p>STM32CubeMX生成的 HAL 库工程中默认已经使能 Systick 及其中断，并配置默认1ms中断一次（1KHz），此配置也可以修改：<br><img src="https://img-blog.csdnimg.cn/20200705202847237.png"><br>默认生成的Systick中断处理函数如图：<br><img src="https://img-blog.csdnimg.cn/20200705203641912.png"><br>Systick中断处理函数中会将计数变量递增：<br><img src="https://img-blog.csdnimg.cn/20200705203744577.png"><br>依托此计数变量，HAL库中提供了一个<strong>堵塞式</strong>的延时函数HAL_Delay()：<br><img src="https://img-blog.csdnimg.cn/20200705203800723.png"></p>
<h1 id="2-RTOS使用堵塞延时的弊端"><a href="#2-RTOS使用堵塞延时的弊端" class="headerlink" title="2. RTOS使用堵塞延时的弊端"></a>2. RTOS使用堵塞延时的弊端</h1><p>HAL_Delay是一个完全死循环等待的延时函数，在RTOS中如果一个任务使用诸如此类的延时函数，<strong>不仅自身浪费了CPU，而且导致其它任务根本得不到调度机会</strong>。</p>
<p>比如，创建下面两个任务，任务task1的优先级高于任务task2：</p>
<pre><code class="c">void task1_entry(void *arg)
&#123;
    printf(&quot;task1 start...\r\n&quot;);
    while(1)
    &#123;
        printf(&quot;task1 is running...\r\n&quot;);
        HAL_Delay(1000);
    &#125;
&#125;

void task2_entry(void *arg)
&#123;
    printf(&quot;task2 start...\r\n&quot;);
    while(1)
    &#123;
        printf(&quot;task2 is running...\r\n&quot;);
        HAL_Delay(1000);
    &#125;
&#125;
</code></pre>
<p>从结果可以看到，task2根本得不到运行：<br><img src="https://img-blog.csdnimg.cn/20200705210459404.png"></p>
<p>为了解决这一问题，RTOS内核就需要向用户提供一个新的延时函数，这个函数是<strong>非堵塞式</strong>的。</p>
<p>堵塞与非堵塞该如何理解呢？</p>
<p>堵塞就是CPU在死循环做一件事情，在别人看来CPU就像堵住了一样~</p>
<p>非堵塞就是当一个任务需要延时的时候，内核会将该任务挂起，然后执行一次抢占式调度，CPU转而去执行当前系统中存在的最高优先级任务，CPU还是照常执行程序~</p>
<blockquote>
<p>注意：任务被挂起就代表着任务从就绪队列中移除，此时调度器去就绪队列中寻找最高优先级任务时，肯定不会找到该任务。</p>
</blockquote>
<h1 id="3-RTOS中的时钟管理"><a href="#3-RTOS中的时钟管理" class="headerlink" title="3. RTOS中的时钟管理"></a>3. RTOS中的时钟管理</h1><h2 id="3-1-时钟节拍的产生"><a href="#3-1-时钟节拍的产生" class="headerlink" title="3.1. 时钟节拍的产生"></a>3.1. 时钟节拍的产生</h2><p>周期性的时钟信号可以由硬件定时器产生，也可以由Systick产生，显然默认已经使能的Systick更好用一点，所以一般情况下都使用Systick产生周期性的时钟信号。</p>
<p>Systick产生信号的频率由Systick的配置决定，默认是1Khz（1ms），可以在开篇所提到的宏定义中修改此配置。</p>
<h2 id="3-2-时钟节拍服务程序"><a href="#3-2-时钟节拍服务程序" class="headerlink" title="3.2. 时钟节拍服务程序"></a>3.2. 时钟节拍服务程序</h2><p>时钟节拍中断处理函数中调用RTOS内核提供的 API 完成对每一个时钟节拍的处理即可，这也是移植一个RTOS内核很重要的一步。</p>
<p>比如TencentOS-tiny中提供的API为 <code>tos_tick_handler</code>，使用方法如下：</p>
<pre><code class="c">void SysTick_Handler(void)
&#123;
    /* USER CODE BEGIN SysTick_IRQn 0 */
    
    /* USER CODE END SysTick_IRQn 0 */
    HAL_IncTick();
    /* USER CODE BEGIN SysTick_IRQn 1 */
    if (tos_knl_is_running())
    &#123;
      tos_knl_irq_enter();
      tos_tick_handler();
      tos_knl_irq_leave();
    &#125;
    /* USER CODE END SysTick_IRQn 1 */
&#125;
</code></pre>
<h2 id="3-3-每个时钟节拍来临时做什么"><a href="#3-3-每个时钟节拍来临时做什么" class="headerlink" title="3.3. 每个时钟节拍来临时做什么"></a>3.3. 每个时钟节拍来临时做什么</h2><p>内核提供的API究竟做了什么呢？我们来一探究竟~</p>
<p>TencentOS-tiny时钟管理的实现在<code>tos_tick.c</code>中，其中对外提供的API源码如下：</p>
<pre><code class="c">__API__ void tos_tick_handler(void)
&#123;
    if (unlikely(!tos_knl_is_running())) &#123;
        return;
    &#125;

    tick_update((k_tick_t)1u);
&#125;
</code></pre>
<p>其中调用了内核函数<code>tick_update</code>，这才是重点，源码如下：</p>
<pre><code class="c">__KNL__ void tick_update(k_tick_t tick)
&#123;
    TOS_CPU_CPSR_ALLOC();
    k_task_t *first, *task, *tmp;

    TOS_CPU_INT_DISABLE();
    k_tick_count += tick;

    if (tos_list_empty(&amp;k_tick_list)) &#123;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    first = TOS_LIST_FIRST_ENTRY(&amp;k_tick_list, k_task_t, tick_list);
    if (first-&gt;tick_expires &lt;= tick) &#123;
        first-&gt;tick_expires = (k_tick_t)0u;
    &#125; else &#123;
        first-&gt;tick_expires -= tick;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    TOS_LIST_FOR_EACH_ENTRY_SAFE(task, tmp, k_task_t, tick_list, &amp;k_tick_list) &#123;
        if (task-&gt;tick_expires &gt; (k_tick_t)0u) &#123;
            break;
        &#125;

        // we are pending for something, but tick&#39;s up, no longer waitting
        pend_task_wakeup(task, PEND_STATE_TIMEOUT);
    &#125;

    TOS_CPU_INT_ENABLE();
&#125;
</code></pre>
<p>从源码中可以看出其中做了三件事：</p>
<ul>
<li>① 将全局计时变量 k_tick_count 递增；</li>
<li>② 进入延时列表的<strong>第一个任务控制块</strong>，将此任务的延时值递减；</li>
<li>③ 循环遍历延时列表，找出所有延时值为0的任务并唤醒，加入到就绪列表中。</li>
</ul>
<p>第一件事没有什么好说的，后两件事的调度算法实现非常牛逼，接下来重点分析！</p>
<h1 id="4-延时列表"><a href="#4-延时列表" class="headerlink" title="4. 延时列表"></a>4. 延时列表</h1><p>古老的UC/OS-II中，在每个时钟节拍来临的时候，采用的调延时调度算法是将任务列表中所有的任务控制块都扫描一遍，将每个任务控制块中的延时值-1，然后判断是否为0，如果该值为0且不是挂起状态，则将任务加入到就绪列表中。</p>
<p>显然，这种算法太low了，耗时，费力。</p>
<p>TencentOS-tiny中进行的第一点优化是，<strong>设计一条专门用于挂载延时任务的延时列表</strong>：</p>
<pre><code class="c">/* list to hold all the tasks delayed or pend for timeout */
extern k_list_t             k_tick_list;
</code></pre>
<p>优化之后，当任务需要延时的时候，系统直接从就绪列表中移除，加入到延时列表中，进而当时钟节拍来临时，只需要遍历延时列表里的任务控制块即可，大大提高了算法的效率，但是还可以更牛逼~</p>
<p>TencentOS-tiny中进行的第二点优化是，<strong>将待延时任务的任务控制块的延时值设置为，与上一个延时任务的差值</strong>：</p>
<pre><code class="c">__STATIC__ void tick_task_place(k_task_t *task, k_tick_t timeout)
&#123;
    TOS_CPU_CPSR_ALLOC();
    k_task_t *curr_task = K_NULL;
    k_tick_t curr_expires, prev_expires = (k_tick_t)0u;

    TOS_CPU_INT_DISABLE();

    task-&gt;tick_expires = timeout;

    TOS_LIST_FOR_EACH_ENTRY(curr_task, k_task_t, tick_list, &amp;k_tick_list) &#123;
        curr_expires = prev_expires + curr_task-&gt;tick_expires;

        if (task-&gt;tick_expires &lt; curr_expires) &#123;
            break;
        &#125;
        if (task-&gt;tick_expires == curr_expires &amp;&amp;
            task-&gt;prio &lt; curr_task-&gt;prio) &#123;
            break;
        &#125;
        prev_expires = curr_expires;
    &#125;
    task-&gt;tick_expires -= prev_expires;
    if (&amp;curr_task-&gt;tick_list != &amp;k_tick_list) &#123;
        curr_task-&gt;tick_expires -= task-&gt;tick_expires;
    &#125;
    tos_list_add_tail(&amp;task-&gt;tick_list, &amp;curr_task-&gt;tick_list);

    TOS_CPU_INT_ENABLE();
&#125;
</code></pre>
<p>优化之后，在时钟节拍的每个中断来临时，只需要将延时列表中的第一个任务控制块的延时值递减即可。</p>
<p>这种方法下可能会存在如下的情况，一堆任务分别需要延时5个tick（task1）、5个tick（task2）、5个tick（task3）、10个tick（task4）、12个tick（task5），当这些任务都加入到延时列表之后记录的差值如下：</p>
<ul>
<li>5(task1)</li>
<li>0(task2-task1)</li>
<li>0(task3-task2)</li>
<li>5(task4-task3)</li>
<li>2(task)</li>
</ul>
<p>当第一个任务task1被递减到0时，后面的两个任务本身差值就是0，所以需要一次延时列表遍历，将任务值为0的任务同时唤醒。</p>
<p>基于此函数，TencentOS-tiny封装了一层API给内核，用来方便的向延时列表中添加任务或者移除任务，如下：</p>
<pre><code class="c">__KNL__ void tick_list_add(k_task_t *task, k_tick_t timeout)
&#123;
    tick_task_place(task, timeout);
    task_state_set_sleeping(task);
&#125;

__KNL__ void tick_list_remove(k_task_t *task)
&#123;
    tick_task_takeoff(task);
    task_state_reset_sleeping(task);
&#125;
</code></pre>
<h1 id="5-任务延时如何实现"><a href="#5-任务延时如何实现" class="headerlink" title="5. 任务延时如何实现"></a>5. 任务延时如何实现</h1><p>经过上述讲述，任务的延时与取消延时已经是水到渠成的事情，非常简单：</p>
<ul>
<li>任务延时实现方法：从就绪列表中移除，加入到延时列表，<strong>并执行一次调度</strong>；</li>
<li>任务取消延时实现方法：从延时列表移除，加入到就绪列表中，<strong>并执行一次调度</strong>；</li>
</ul>
<p>上源码，先来看任务延时的实现（省略了一堆参数检查）：</p>
<pre><code class="c">__API__ k_err_t tos_task_delay(k_tick_t delay)
&#123;
    TOS_CPU_CPSR_ALLOC();

    //进入临界段
    TOS_CPU_INT_DISABLE();

    tick_list_add(k_curr_task, delay);
    readyqueue_remove(k_curr_task);

    TOS_CPU_INT_ENABLE();
    //退出临界段
    
    //执行一次调度，从就绪列表中取出最高优先级的任务执行    
    knl_sched();

    return K_ERR_NONE;
&#125;
</code></pre>
<p>再来看看任务取消延时的实现（省略了一堆参数检查）：</p>
<pre><code class="c">__API__ k_err_t tos_task_delay_abort(k_task_t *task)
&#123;
    TOS_CPU_CPSR_ALLOC();

    TOS_CPU_INT_DISABLE();

    tick_list_remove(task);
    readyqueue_add(task);

    TOS_CPU_INT_ENABLE();
    knl_sched();

    return K_ERR_NONE;
&#125;
</code></pre>
<h1 id="6-时间管理"><a href="#6-时间管理" class="headerlink" title="6. 时间管理"></a>6. 时间管理</h1><p>之前任务延时的API都是以tick个数为单位的，为了更加符合用户习惯，TencentOS-ting中提供了一系列额外的时间相关API，在<code>tos_time.c</code>中。</p>
<p>这些额外的时间相关API都<strong>依赖一个宏定义</strong>，告诉内核1s内有多少个tick，如下，在<code>tos_config.h</code>中配置：</p>
<pre><code class="c">#define TOS_CFG_CPU_TICK_PER_SECOND     1000u
</code></pre>
<p>比如：</p>
<p>① tick数和ms进行转化的API：</p>
<pre><code class="c">__API__ k_time_t tos_tick2millisec(k_tick_t tick)
&#123;
    return (k_time_t)(tick * K_TIME_MILLISEC_PER_SEC / TOS_CFG_CPU_TICK_PER_SECOND);
&#125;

__API__ k_tick_t tos_millisec2tick(k_time_t ms)
&#123;
    return ((k_tick_t)ms * TOS_CFG_CPU_TICK_PER_SECOND / K_TIME_MILLISEC_PER_SEC);
&#125;
</code></pre>
<p>② 以ms数为单位的任务延时API：</p>
<pre><code class="c">__API__ k_err_t tos_sleep_ms(k_time_t ms)
&#123;
    return tos_task_delay(tos_millisec2tick(ms));
&#125;
</code></pre>
<p>③ 以年月日为单位的任务延时API：</p>
<pre><code class="c">__API__ k_err_t tos_sleep_hmsm(k_time_t hour, k_time_t minute, k_time_t second, k_time_t millisec)
&#123;
    return tos_task_delay(time_hmsm2tick(hour, minute, second, millisec));
&#125;
</code></pre>
<h1 id="7-空闲任务"><a href="#7-空闲任务" class="headerlink" title="7. 空闲任务"></a>7. 空闲任务</h1><p>当系统中的所有任务都在延时列表中时，那就绪列表岂不是没有东西了？？？CPU岂不是凉了？？？待会用事实说话。</p>
<p>为了防止这种情况，<strong>RTOS内核必须设置一个空闲任务，目的就是让CPU永远要有任务执行</strong>，如果想玩的高级一点，还可以在空闲任务中来点骚操作，比如：</p>
<ul>
<li>进入低功耗模式</li>
<li>检查释放系统内存</li>
<li>……</li>
</ul>
<p>TencentOS-tiny中空闲任务的实现在<code>tos_sys.c</code>中：</p>
<pre><code class="c">__STATIC__ void knl_idle_entry(void *arg)
&#123;
    arg = arg; // make compiler happy

    while (K_TRUE) &#123;
#if TOS_CFG_TASK_DYNAMIC_CREATE_EN &gt; 0u
        task_free_all();
#endif

#if TOS_CFG_PWR_MGR_EN &gt; 0u
        pm_power_manager();
#endif
    &#125;
&#125;

__KNL__ k_err_t knl_idle_init(void)
&#123;
    return tos_task_create(&amp;k_idle_task, &quot;idle&quot;,
            knl_idle_entry, K_NULL,
            K_TASK_PRIO_IDLE,
            k_idle_task_stk_addr,
            k_idle_task_stk_size,
            0);
&#125;
</code></pre>
<p>空闲任务的优先级当然是系统所支持的最低优先级：</p>
<pre><code class="c">#define K_TASK_PRIO_IDLE (k_prio_t)(TOS_CFG_TASK_PRIO_MAX - (k_prio_t)1u)
</code></pre>
<p>空闲任务的任务栈大小可以在<code>tos_config.h</code>中配置：</p>
<pre><code class="c">#define TOS_CFG_IDLE_TASK_STK_SIZE      512u
</code></pre>
<p>接下来演示一下在TencentOS-tiny中如果没有空闲中断，会发生什么。</p>
<p>① 将 knl_idle_init 中创建空闲任务的代码屏蔽，改为<code>return 0</code></p>
<p>② 在tos_config.h中使能最后一屏的功能：</p>
<pre><code class="c">#define TOS_CFG_FAULT_BACKTRACE_EN      1u
</code></pre>
<p>③ 在中断文件中屏蔽中断处理函数<code>HardFault_Handler</code>，防止冲突；</p>
<p>编译，下载程序，在串口助手中查看结果：<br><img src="https://img-blog.csdnimg.cn/20200706201924342.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01jdWxvdmVyNjY2,size_16,color_FFFFFF,t_70"></p>
<h1 id="8-软件定时器"><a href="#8-软件定时器" class="headerlink" title="8. 软件定时器"></a>8. 软件定时器</h1><p>软件定时器的核心原理就是根据tick数判断是否超时，如果超时拉起定时器回调函数进行执行。基于RTOS内核中的时钟管理，可以方便扩展出软件定时器功能。在每个时钟节拍来临的时候，对系统中存在的软件定时器一并进行处理。</p>
<p>TencentOS-tiny中的软件定时器支持两种模式，通过<code>tos_config.h</code>中的宏定义来选择：</p>
<pre><code class="c">#define TOS_CFG_TIMER_AS_PROC           1u
</code></pre>
<ul>
<li>宏定义使能：配置软件定时器为回调函数模式；</li>
<li>宏定义关闭：配置软件定时器为任务模式；</li>
</ul>
<p>当配置为第一种模式时，在时钟节拍处理程序中，对应的软件定时器处理任务被使能：</p>
<pre><code class="c">__API__ void tos_tick_handler(void)
&#123;
    if (unlikely(!tos_knl_is_running())) &#123;
        return;
    &#125;

    tick_update((k_tick_t)1u);

#if TOS_CFG_TIMER_EN &gt; 0u &amp;&amp; TOS_CFG_TIMER_AS_PROC &gt; 0u
    timer_update();
#endif

#if TOS_CFG_ROUND_ROBIN_EN &gt; 0u
    robin_sched(k_curr_task-&gt;prio);
#endif
&#125;
</code></pre>
<p>其中软件定时器处理函数为<code>timer_update</code>，源码在<code>tos_timer.c</code>中：</p>
<pre><code class="c">__KNL__ void timer_update(void)
&#123;
    k_timer_t *tmr, *tmp;

    if (k_timer_ctl.next_expires &gt; k_tick_count) &#123; // not yet
        return;
    &#125;

    tos_knl_sched_lock();

    TOS_LIST_FOR_EACH_ENTRY_SAFE(tmr, tmp, k_timer_t, list, &amp;k_timer_ctl.list) &#123;
        if (tmr-&gt;expires &gt; k_tick_count) &#123;
            break;
        &#125;

        // time&#39;s up
        timer_takeoff(tmr);

        if (tmr-&gt;opt == TOS_OPT_TIMER_PERIODIC) &#123;
            tmr-&gt;expires = tmr-&gt;period;
            timer_place(tmr);
        &#125; else &#123;
            tmr-&gt;state = TIMER_STATE_COMPLETED;
        &#125;

        (*tmr-&gt;cb)(tmr-&gt;cb_arg);
    &#125;

    tos_knl_sched_unlock();
&#125;
</code></pre>
<p>其中有一点需要特别注意：</p>
<p><strong>定时器回调函数被调用时，调度器是处于上锁状态的，当回调函数执行完返回之后，调度器才解锁</strong>。</p>
<p>所以在编写软件定时器回调函数的时候，不用担心发生任务调度的情况。</p>
<h1 id="9-时间片调度算法"><a href="#9-时间片调度算法" class="headerlink" title="9. 时间片调度算法"></a>9. 时间片调度算法</h1><p>时间片调度算法用来处理<strong>系统中同时存在两个优先级相同的就绪任务，且都不让出CPU</strong>的情况，分别按照任务设置的时间片tick数轮流执行。</p>
<p>TencentOS-tiny控制是否开启时间片调度的宏定义为：</p>
<pre><code class="c">#define TOS_CFG_ROUND_ROBIN_EN          1u
</code></pre>
<p>开启时间片调度后，在每个时钟节拍来临的时候，对当前任务优先级进行时间片调度：</p>
<pre><code class="c">__API__ void tos_tick_handler(void)
&#123;
    if (unlikely(!tos_knl_is_running())) &#123;
        return;
    &#125;

    tick_update((k_tick_t)1u);

#if TOS_CFG_TIMER_EN &gt; 0u &amp;&amp; TOS_CFG_TIMER_AS_PROC &gt; 0u
    timer_update();
#endif

#if TOS_CFG_ROUND_ROBIN_EN &gt; 0u
    robin_sched(k_curr_task-&gt;prio);
#endif
&#125;
</code></pre>
<p>其中处理时间片调度的函数为<code>robin_sched</code>，在<code>tos_robin.c</code>中，源码如下：</p>
<pre><code class="c">__KNL__ void robin_sched(k_prio_t prio)
&#123;
    TOS_CPU_CPSR_ALLOC();
    k_task_t *task;

    TOS_CPU_INT_DISABLE();

    task = readyqueue_first_task_get(prio);
    if (!task || knl_is_idle(task)) &#123;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    if (readyqueue_is_prio_onlyone(prio)) &#123;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    if (knl_is_sched_locked()) &#123;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    if (task-&gt;timeslice &gt; (k_timeslice_t)0u) &#123;
        --task-&gt;timeslice;
    &#125;

    if (task-&gt;timeslice &gt; (k_timeslice_t)0u) &#123;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    readyqueue_move_head_to_tail(k_curr_task-&gt;prio);

    task = readyqueue_first_task_get(prio);
    if (task-&gt;timeslice_reload == (k_timeslice_t)0u) &#123;
        task-&gt;timeslice = k_robin_default_timeslice;
    &#125; else &#123;
        task-&gt;timeslice = task-&gt;timeslice_reload;
    &#125;

    TOS_CPU_INT_ENABLE();
    knl_sched();
&#125;
</code></pre>
<p>从源码中可以看到，时间片调度算法的实现非常简单：当时钟节拍来临的时候，将就绪列表中第一个任务控制块的时间片值递减，如果递减到0，则移到就绪列表的队尾去，让出此次执行机会，内核发生调度。</p>
<p>接下来用一个实例说话，编写两个task任务，采用开篇提到的堵塞延时，不让出CPU：</p>
<pre><code class="c">void task1_entry(void *arg)
&#123;
    printf(&quot;task1 start...\r\n&quot;);
    while(1)
    &#123;
        printf(&quot;task1 is running...\r\n&quot;);
        HAL_Delay(1000);
    &#125;
&#125;

void task2_entry(void *arg)
&#123;
    printf(&quot;task2 start...\r\n&quot;);
    while(1)
    &#123;
        printf(&quot;task2 is running...\r\n&quot;);
        HAL_Delay(1000);
    &#125;
&#125;
</code></pre>
<p>创建任务的时候设置优先级相同，时间片参数为10个tick：</p>
<pre><code class="c">tos_task_create(&amp;task1, &quot;task1&quot;, task1_entry, NULL, 2, task1_stack, sizeof(task1_stack), 10);
printf(&quot;task1 create success\r\n&quot;);
tos_task_create(&amp;task2, &quot;task2&quot;, task2_entry, NULL, 2, task2_stack, sizeof(task2_stack), 10);
printf(&quot;task2 create success\r\n&quot;);
</code></pre>
<p>首先在 tos_config.h 中将时间片调度关掉，观察实验结果，任务2虽然优先级相同，但是根本得不到运行：<br><img src="https://img-blog.csdnimg.cn/2020070711523184.png"><br>在 tos_config.h 中将时间片调度开启，观察实验结果：<br><img src="https://img-blog.csdnimg.cn/2020070711533276.png"><br>可以看到两个任务都不让出CPU，因为两个任务的优先级想通过，所以系统依然根据设置的时间片tick数进行轮流调度运行，这也是进一步符合RTOS这种实时操作系统的调度要求。</p>
<h1 id="10-总结"><a href="#10-总结" class="headerlink" title="10. 总结"></a>10. 总结</h1><p>本文内容比较多，最后来总结一下比较重要的点：</p>
<p>① RTOS内核需要时钟节拍来周期性的处理任务延时、软件定时器、时间片调度的逻辑，所以<strong>移植时必须要提供时钟节拍</strong>。</p>
<p>② RTOS内核提供以tick数为单位的延时API，和以ms为单位的延时API，因为不同的平台上每个tick可能对应的时长不一样，所以<strong>建议应用程序采用以ms为单位的API</strong>，更加通用。</p>
<p>③ 软件定时器采用回调函数模式时，执行回调函数的时候系统调度处于上锁状态，执行完毕之后才会解锁，<strong>不用担心会发生任务切换</strong>。</p>
<p>④ 调用任务延时函数的时候，不仅仅会使当前任务延时一段时间，更重要的是<strong>会发生一次调度</strong>，使低优先级的任务运行。</p>
<p>本期文章就到这儿了~我是喜欢玩板子的小码农Mculover666，下期文章再见！</p>
<p><font color="red"><strong>接收更多精彩文章及资源推送，欢迎订阅我的微信公众号：『mculover666』。</strong></font><br><img src="https://img-blog.csdnimg.cn/20200202092055136.png"></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Mculover666</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.mculover666.cn/posts/2848765993/">http://www.mculover666.cn/posts/2848765993/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Mculover666</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                                    <span class="chip bg-color">RTOS内功修炼记</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/we-chat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    
    <div class="livere-card card" data-aos="fade-up">
    <!-- 来必力City版安装代码 -->
    <div id="lv-container" class="card-content" data-id="city" data-uid="MTAyMC80Njg0OS8yMzM1MA">
        <script type="text/javascript">
            (function (d, s) {
                let j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') {
                    return;
                }

                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript。</noscript>
    </div>
    <!-- City版安装代码已完成 -->
</div>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/2361665440/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/9.jpg" class="responsive-img" alt="05-任务间同步机制的实现，万变不离其宗">
                        
                        <span class="card-title">05-任务间同步机制的实现，万变不离其宗</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            RTOS内功修炼记
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-08-01
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RTOS/" class="post-category">
                                    RTOS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                        <span class="chip bg-color">RTOS内功修炼记</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/199163223/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/15.jpg" class="responsive-img" alt="03-内核到底是如何管理中断的">
                        
                        <span class="card-title">03-内核到底是如何管理中断的</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            RTOS内功修炼记
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-08-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RTOS/" class="post-category">
                                    RTOS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                        <span class="chip bg-color">RTOS内功修炼记</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2016-2021</span>
            
            <span id="year">2016</span>
            <a href="/about" target="_blank">Mculover666</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">118.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2016";
                    var startMonth = "8";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="https://beian.miit.gov.cn" target="_blank">陇ICP备19002222号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Mculover666" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:mculover666@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2412828003" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2412828003" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/wang-shi-wei-67-38/activities" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/wang-shi-wei-67-38/activities" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?6e1efa0988723a1db6356535db2ae6bd";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
